package com.ellecity06.common.http

import android.app.Dialog
import com.ellecity06.common.helper.NetworkHelper
import com.ellecity06.common.http.entity.ApiResponse
import com.ellecity06.common.http.exception.ApiException
import com.ellecity06.common.http.exception.ExceptionHandle
import com.ellecity06.common.http.exception.HttpErrorException
import com.ellecity06.common.utils.ToastUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.onCompletion
import kotlinx.coroutines.flow.onStart

/**
 * @author zavier
 * @time 2025/3/11 16:16
 * @des
 */
sealed class ApiState {
    data class SuccessFull<T>(val data: ApiResponse<T>) : ApiState()
    data class Error(val e: Throwable) : ApiState()
    data class TokenExpired(val message: String) : ApiState()

}

suspend fun <T> launchFlow2(
    body: suspend () -> ApiResponse<T>,
    loading: Dialog? = null,
    error: suspend (Throwable) -> Unit = { t ->
        //默认异常处理，子类可以进行覆写
        ToastUtils.show(t.message ?: "系统异常")
    }
): Flow<ApiState> {
    return flow {
        if (!NetworkHelper.isNetworkConnected()) {
            throw HttpErrorException(message = "当前网络不可用")
        } else {
            emit(body())
        }
    }.flowOn(Dispatchers.IO).onStart {
        loading?.show()
    }.catch {
        val exception = ExceptionHandle.handleException(e = it)
        error.invoke(exception)
    }.onCompletion {
        loading?.dismiss()
    }.map {
        if (it.isSuccess) {
            ApiState.SuccessFull<T>(it)

        } else {
            if (it.tokenExpired) {
                ApiState.TokenExpired(it.msg ?: "登录失效了，请重新登录！")

            } else {
                ApiState.Error(ApiException(it.msg ?: "数据异常", it.code ?: -1))
            }
        }

    }


}